//
//  UIImage.swift
//  Created by Visitor on 2017/5/22.
//  Copyright © 2017年 万利. All rights reserved.
//

//<Error>: CGContextSaveGState: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.
//解决方案: 
/*
 出错原因：设置app的状态栏样式的使用使用了旧的方式，在info.plist里面设置了View controller-based status bar appearance为NO，默认为YES，一般式iOS6的时候使用这种方式，iOS7，8也兼容，但是到了iOS9就报了警告。
 */

import UIKit
extension UIImage{

    func scaleToSize(scaleSize: CGSize) ->UIImage{
        let w = scaleSize.width
        let h = scaleSize.height
        let img = self.cgImage
        let pixelBuffer = malloc(img!.bytesPerRow * img!.height)
        
        let colorSpace = CGColorSpaceCreateDeviceRGB();
        let ctx = CGContext(data: pixelBuffer,
                            width: Int(w),
                            height: Int(h),
                            bitsPerComponent: 8,
                            bytesPerRow: 4 * Int(w),
                            space: colorSpace,
                            bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue)

        draw(in: CGRect(x: 0, y: 0, width: w, height: h))
        let  imageMasked = ctx!.makeImage();
        return UIImage(cgImage: imageMasked!)
    }

}
